#!/usr/bin/python
#coding=utf-8

import os;
from video_lib.video_db import db_init
from video_lib.video_db.movie_queue import movie_queue
from sqlalchemy.orm import sessionmaker
from sqlalchemy import and_
import datetime
class Convert:
#create session
        ConvertSession                 	= sessionmaker(bind= db_init.engine)
        convert_session      	        = ConvertSession();

	def __init__(self,video_queue_element):
		self.video_queue_e		=video_queue_element;
		self.video_file			="";
		self.convert_status		='convert_wait'

		Convert.convert_session.add(self.video_queue_e );

	def begin_convert(self):
		self.video_queue_e.video_status = 'converting'
		Convert.convert_session.commit();
		return;

	def video_convert(self):
		cmd 	 = 	"./convert.sh "
		cmd	+=	self.video_queue_e.video_downloadname + " ";
		cmd     +=	"/home/work/convert/"+str(datetime.date.today())+"/" + " ";
		cmd	+=	os.path.basename(self.video_queue_e.video_downloadname)
		re  	 = 	os.system(cmd);
		if re == 0:
			self.convert_status			=	'convert_done';
			self.video_queue_e.video_convertname 	=	"/home/work/convert/"+str(datetime.date.today())+"/" + os.path.basename(self.video_queue_e.video_downloadname)+".m4v"
		else:
			self.convert_status	=	'convert_fail';
		
		return;

	def end_convert(self):
		self.video_queue_e.video_status = self.convert_status;
		Convert.convert_session.commit()
		return;

if __name__ == '__main__':
	for row in Convert.convert_session.query(movie_queue).filter(movie_queue.video_status == 'wait_convert'):
		p = Convert(row);
		p.begin_convert()
		p.video_convert();
		p.end_convert();

